﻿#include "blinklabel.h"

BlinkLabel::BlinkLabel(QWidget* parent, const QColor& color)
    : QLabel(parent)
    , set_color_(color)
{
    setAutoFillBackground(true);
    original_color_ = this->palette().brightText().color(); //读取字体原本的颜色
    connect(&timer_, SIGNAL(timeout()), this, SLOT(sltTimeout()));
}

BlinkLabel::~BlinkLabel()
{
    timer_.stop();
}

void BlinkLabel::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event)

    // 计算文本绘制的起始坐标
    QFontMetrics metrics(font());
    int x = (width() - metrics.horizontalAdvance(this->text())) / 2;
    int y = (height() + metrics.ascent() - metrics.descent()) / 2;

    QPainter painter(this);
    for (int i = 0; i < this->text().size(); ++i) {
        if (is_alarm_) {
            if (is_change_text_color_) {
                painter.setPen(set_color_); //设为设置的颜色
            } else {
                painter.setPen(this->palette().window().color()); //设为背景色
            }
        } else {
            painter.setPen(original_color_);
        }
        // 单个字符绘制
        painter.drawText(x, y, QString(this->text()[i]));

        // 计算下一个字符的x坐标起始点
        x += metrics.horizontalAdvance(this->text()[i]);
    }
}

/**
 * @brief BlinkLabel::alarm 每500ms反转一次
 * @param isAlarm
 */
void BlinkLabel::alarm(bool isAlarm)
{
    is_alarm_ = isAlarm;
    if (isAlarm) {
        if (!timer_.isActive()) {
            timer_.start(500);
        }
    } else {
        timer_.stop();
        this->update();
    }
}

void BlinkLabel::sltTimeout()
{
    is_change_text_color_ = !is_change_text_color_;
    this->update();
}
